const express = require('express');
const mysql = require('mysql');

const app = express();
const multer  = require('multer');
const upload = multer({ dest: 'uploads/' });
const fs = require('fs');
const path = require('path');

// 创建数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '20030823zM@',
  database: 'iot'
});

// 连接数据库
connection.connect();
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//告警
app.get('/selectById1/data', (req, res) => {
  const id = req.query.id;
  // 处理接收到的参数
  const sql = 'SELECT * FROM gaoj WHERE id = ?';
  connection.query(sql, [id], (error, results) => {
    if (error) throw error;
    res.json(results);
  });
  // res.send('Received id: ' + id);
});
app.get('/api1/data', (req, res) => {
  const sql = 'SELECT * FROM gaoj';
  connection.query(sql, (error, results) => {
    if (error) throw error;
    res.json(results);
  });
});



app.post('/upload', upload.single('image'), (req, res) => {
  const imageUrl = req.file.path; // 保存图片路径
  const filename = path.basename(imageUrl);
  // const parts = imageUrl.split('/');
// const filename = parts[parts.length - 1];
  console.log("图片路径："+imageUrl);
  console.log("文件名："+filename)
  res.send(filename);
  // 插入刚上传的文件信息到数据库
  // connection.query('INSERT INTO images (filename, filepath) VALUES (?, ?)', [req.file.originalname, imageUrl], (err, result) => {
  //   if (err) {
  //     console.log('Error inserting file into database: ', err);
  //     res.status(500).send('Error inserting file into database');
  //   } else {
  //     console.log('File inserted into database successfully');
  //     res.send(filename);
  //   }
  // });
});
app.get('/images', (req, res) => {
  // 返回所有图片信息，用于展示给所有用户
});
app.get('/selectById/data', (req, res) => {
  const id = req.query.id;
  // 处理接收到的参数
  const sql = 'SELECT * FROM punch WHERE id = ?';
  connection.query(sql, [id], (error, results) => {
    if (error) throw error;
    res.json(results);
  });
  // res.send('Received id: ' + id);
});
app.post('/receiveFormData', (req, res) => {
  const {dkwz,qsxm,dkr,sspz,dkrq}=req.body;
 const time=req.body.dkrq
  console.log("时间："+time)
  const sql = 'INSERT INTO punch (dkwz, qsxm,dkr,sspz,dkrq) VALUES (?, ?, ?, ?, ?)'; 
  const values = [dkwz, qsxm,dkr,sspz,dkrq];
  connection.query(sql, values, (err, result) => { 
    if (err) { 
      console.error(err); 
      res.status(500).send('Error inserting data into database'); 
    } else { 
      console.log('Data inserted successfully');
       res.send('新增成功!'); 
      } }); });

// 定义接口，从数据库获取数据
app.get('/api/data', (req, res) => {
  const sql = 'SELECT * FROM punch';
  connection.query(sql, (error, results) => {
    if (error) throw error;
    res.json(results);
  });
});
//定义接口，将图片渲染到页面上
// 创建一个接口用于查询图片
app.get('/getimage/:imageName', (req, res) => {
  const imageName = req.params.imageName;
  const imagePath = path.join(__dirname, 'uploads', imageName);

  fs.readFile(imagePath, (err, data) => {
    if (err) {
      console.log('Error reading image file: ', err);
      res.status(500).send('Error reading image file');
    } else {
      res.writeHead(200, { 'Content-Type': 'image/jpeg' }); // 根据实际图片类型设置 Content-Type
      res.end(data);
    }
  });
});
// app.get('/getimage', (req, res) => {
//   connection.query('SELECT filepath FROM images', (err, results) => {
//     if (err) {
//       console.log('Error retrieving images from database: ', err);
//       res.status(500).send('Error retrieving images from database');
//     } else {
//       res.json(results); // 将查询结果以 JSON 格式返回
//     }
//   });
// });


// 启动服务器
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});